﻿#include <iostream>
#include <charconv>
#include <thread>

#include "server/server/WorkerPool.h"
#include "server/server/SignalHandler.h"
#include "server/server/Worker.h"

#define SERVER_VERSION "1.0.0"

int main(const int argc, char* argv[])
{
    if (argc < 2 || argc > 3)
    {
        std::cerr << "Usage: server <port> [worker_count]\n";
        return 1;
    }

    uint16_t port;
    if (const auto [ptr, ec] = std::from_chars(argv[1], argv[1] + std::strlen(argv[1]), port);
        ec != std::errc() || ptr != argv[1] + std::strlen(argv[1]))
    {
        std::cerr << "Invalid port number\n";
        return 1;
    }

    size_t worker_count = 0;  // 0 means use default (hardware concurrency)
    if (argc == 3)
    {
        if (const auto [ptr, ec] = std::from_chars(argv[2], argv[2] + std::strlen(argv[2]), worker_count);
            ec != std::errc() || ptr != argv[2] + std::strlen(argv[2]))
        {
            std::cerr << "Invalid worker count\n";
            return 1;
        }
    }

    try
    {
        std::cout << "Starting server version " << SERVER_VERSION << std::endl;

        const auto workerPool = WorkerPool::getInstance();

        if (!workerPool->startAll(port, worker_count))
        {
            std::cerr << "Failed to start server on port " << port << "\n";
            return 1;
        }

        std::cout << "Server started on port " << port << " with "
                  << (worker_count == 0 ? "default" : std::to_string(worker_count))
                  << " worker(s)\n";

        // 等待信号以优雅地关闭服务器
        SignalHandler::getInstance().waitForSignal();

        std::cout << "Received shutdown signal. Initiating graceful shutdown...\n";

        // 停止 WorkerPool
        std::cout << "Send stop to WorkerPool...\n";
        workerPool->requestStopAll();

        // TODO: Validating all server status.
        // TODO: Force stop server function.
    }
    catch (const std::exception& e)
    {
        std::cerr << "Fatal exception: " << e.what() << "\n";
        return 1;
    }

    return 0;
}
